package com.treeliked.netdiskdemo.controller;

import com.treeliked.netdiskdemo.model.Response;
import com.treeliked.netdiskdemo.model.ResultCode;
import com.treeliked.netdiskdemo.model.dataobject.File;
import com.treeliked.netdiskdemo.service.FolderService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * folder api
 *
 * @author lqs2
 * @date 2018/12/7, Fri
 */
@RestController
@RequestMapping("/api/folder")
public class FolderController {


    private static Logger log = LoggerFactory.getLogger(FolderController.class);

    private final FolderService folderService;

    @Autowired
    public FolderController(FolderService folderService) {
        this.folderService = folderService;
    }

    @GetMapping("/showFolder")
    public Response showFolderContent(@RequestParam("un") String username, String path, HttpSession session) {
        Response resp = new Response();
        try {
            List<File> files = folderService.showFile(path, username);
            resp.setData(files);
            resp.setCode(ResultCode.SUCCESS);
            resp.setMessage(path);
        } catch (Exception e) {
            log.error("", e);
            resp.setCode(ResultCode.INTERNAL_SERVER_ERROR);
            resp.setMessage(e.getMessage());
        }
        return resp;
    }

    @GetMapping("/createFolder")
    public Response makeDirectory(@RequestParam("un") String username, String path, String name) {
        Response resp = new Response();
        try {
            folderService.createFolder(path, name, username, resp);
        } catch (Exception e) {
            log.error("", e);
            resp.setCode(ResultCode.INTERNAL_SERVER_ERROR);
            resp.setMessage(e.getMessage());
        }
        return resp;
    }

    @GetMapping(value = "/rm")
    public Response removeDir(@Param("path") String path, @Param("id") String id) {
        Response resp = new Response();
        try {
            folderService.deleteFolder(path, id, resp);
            org.apache.commons.io.FileUtils.deleteDirectory(new java.io.File(path));
            resp.setCode(ResultCode.SUCCESS);
            resp.setMessage("文件夹【" + path + "】删除成功");
        } catch (Exception e) {
            log.error("", e);
            resp.setCode(ResultCode.INTERNAL_SERVER_ERROR);
            resp.setMessage("文件夹【" + path + "】删除失败");
        }
        return resp;
    }
}
